package springframework.bean;

import com.qumoyugo.springframework.beans.BeansException;
import com.qumoyugo.springframework.beans.factory.FactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Cedric
 * @date 2021/11/26 15:30
 * @description 定义一个FactoryBean作为UserDao的代理类
 */
public class ProxyFactoryBean implements FactoryBean<IUserDao> {

    @Override
    public IUserDao getObject() throws BeansException {
        InvocationHandler handler = (proxy, method, args) -> {
            // 排除toString方法
            if ("toString".equals(method.getName())) {
                return this.toString();
            }
            Map<String, String> hashMap = new HashMap<>();
            hashMap.put("10001", "cedric");
            hashMap.put("10002", "it-farmer");
            return "你被代理了" + method.getName() + ":" + hashMap.get(args[0].toString());
        };
        return (IUserDao) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{IUserDao.class}, handler);
    }

    @Override
    public Class<?> getObjectType() {
        return IUserDao.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
